package com.bitcola.exchange.push.http;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * 根据IP地址获取详细的地域信息
 *
 */
public class IPUtil {


    // 测试
    public static void main(String[] args) {
        System.out.println(getUserLocation("182.148.57.21"));
    }


    public static String getUserLocation(String userIp){
        if ("0:0:0:0:0:0:0:1".equals(userIp)) return "localhost";
        if ("localhost".equals(userIp)) return "localhost";
        if ("127.0.0.1".equals(userIp)) return "localhost";
        if (userIp.startsWith("192.168.")) return userIp;
        try {
            String url = "http://opendata.baidu.com/api.php?query=" + userIp;
            url += "&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=gbk&format=json";
            HttpUtil.get(url);
            String result =  HttpUtil.get(url);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject obj = jsonObject.getJSONArray("data").getJSONObject(0);
            String location = obj.getString("location");
            return location;
        }catch (Exception e){
            //e.printStackTrace();
            return "";
        }
    }








}